package _022_1_29

/*
1.特殊情况特殊处理，不要老是想着特殊情况也很普通情况一起处理了。
2.下标是否和你想要处理的情况一样，就是你想要下标几到下标几的数据他是否和你想的一样
3.如果思路没问题，就按着思路来
4.特殊情况特殊处理
*/
func checkWordSizeIsOverflow2(allWordSize int, wordNum int, maxWidth int) bool {
	if allWordSize+wordNum-1 > maxWidth {
		return true
	}
	return false
}

func distributeSpaceNum2(spaceSize int, wordCount int, end int, words []string) []int {
	spaces := make([]int, 0)

	if end == len(words)-1 {
		for i := 0; i < wordCount-1; i++ {
			spaces = append(spaces, 1)
		}
		spaces = append(spaces, spaceSize-wordCount+1)
		return spaces
	}

	if wordCount == 1 {
		spaces = append(spaces, spaceSize)
		return spaces
	}

	_tempSize := spaceSize / (wordCount - 1)
	for i := 0; i < wordCount-1; i++ {
		spaces = append(spaces, _tempSize)
	}
	for i := 0; i < spaceSize%(wordCount-1); i++ {
		spaces[i] += 1
	}

	return spaces
}

//1 2 3 4 5
//1 2 3 4
//1
func createLineStr2(words []string, beg int, end int, allWordsCharacterSize int, maxWidth int) string {
	spaces := distributeSpaceNum2(maxWidth-allWordsCharacterSize, end-beg+1, end, words)
	resultStr := ""

	if end == len(words)-1 {
		for i := 0; i < len(spaces); i++ {
			resultStr += words[beg+i]
			for k := 0; k < spaces[i]; k++ {
				resultStr += " "
			}
		}

		return resultStr
	}

	for i := 0; i < len(spaces); i++ {
		resultStr += words[beg+i]
		for j := 0; j < spaces[i]; j++ {
			resultStr += " "
		}
	}

	if (end - beg) >= 1 {
		resultStr += words[end]
	}
	return resultStr
}

func fullJustify2(words []string, maxWidth int) []string {
	beginId := 0
	result := make([]string, 0)

	for beginId < len(words) {

		tempSize := 0
		oldBegId := beginId
		for ; beginId < len(words); beginId++ {
			tempSize += len(words[beginId])
			if checkWordSizeIsOverflow(tempSize, beginId-oldBegId+1, maxWidth) {
				tempSize -= len(words[beginId])
				beginId--
				break
			}
		}
		if beginId == len(words) {
			beginId--
		}
		str := createLineStr(words, oldBegId, beginId, tempSize, maxWidth)
		beginId++
		result = append(result, str)
	}
	return result
}
